/**
 * 学校信息上下文
 * 用于在整个应用中共享当前选中的学校信息
 */

'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { School } from '@/types/api';
import localStorageKeys from '@/utils/localStorageKeys';

interface SchoolContextValue {
  /** 当前学校信息 */
  currentSchool: School | null;
  /** 设置当前学校 */
  setCurrentSchool: (school: School | null) => void;
  /** 论坛链接 */
  forumLink: string;
  /** 论坛名称 */
  forumName: string;
}

const SchoolContext = createContext<SchoolContextValue | undefined>(undefined);

interface SchoolProviderProps {
  children: ReactNode;
}

/**
 * 学校信息提供者组件
 */
export const SchoolProvider: React.FC<SchoolProviderProps> = ({ children }) => {
  const [currentSchool, setCurrentSchoolState] = useState<School | null>(null);

  // 从 localStorage 加载学校信息
  useEffect(() => {
    try {
      const saved = localStorage.getItem(localStorageKeys.current_school);
      if (saved) {
        const school = JSON.parse(saved) as School;
        setCurrentSchoolState(school);
      }
    } catch (error) {
      console.error('Failed to load school info from localStorage:', error);
    }
  }, []);

  // 设置学校信息并保存到 localStorage
  const setCurrentSchool = (school: School | null) => {
    setCurrentSchoolState(school);
    try {
      if (school) {
        localStorage.setItem(localStorageKeys.current_school, JSON.stringify(school));
      } else {
        localStorage.removeItem(localStorageKeys.current_school);
      }
    } catch (error) {
      console.error('Failed to save school info to localStorage:', error);
    }
  };

  // 获取论坛链接和名称,如果没有学校信息则返回默认值
  const forumLink = currentSchool?.forum_link || '';
  const forumName = currentSchool?.forum_name || 'UU论坛';

  const value: SchoolContextValue = {
    currentSchool,
    setCurrentSchool,
    forumLink,
    forumName,
  };

  return <SchoolContext.Provider value={value}>{children}</SchoolContext.Provider>;
};

/**
 * 使用学校信息的 Hook
 */
export const useSchool = (): SchoolContextValue => {
  const context = useContext(SchoolContext);
  if (context === undefined) {
    throw new Error('useSchool must be used within a SchoolProvider');
  }
  return context;
};
